package com.inf.controller;

import com.inf.featureCompare.FeatureCompare;
import com.inf.service.PartnerAnalysisService;
import com.inf.service.PersonService;
import com.inf.service.PidVidService;
import com.inf.utils.FeatureUtil;
import com.inf.utils.HBaseUtil;
import com.inf.utils.Tools;
import com.inf.vo.*;
import com.sun.jersey.core.util.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;


/**
 * Created by zhangbn on 2018/11/8.
 */
@RestController
@RequestMapping("/personface/partner")
public class PartnerAnalysisController {

    Logger log = LoggerFactory.getLogger(PartnerAnalysisController.class);

    @Autowired
    PartnerAnalysisService partnerAnalysisService;

    @Autowired
    private PersonService personService;

    @Autowired
    private PidVidService pidVidService;

    @Autowired
    private JedisPool jedisPool;


    /**
     * 获得同行人
     *
     * @param vo
     * @return
     */
    @RequestMapping(value = "/getpartner", method = RequestMethod.POST)
    public ResponseVo partnerAnalysis(@RequestBody ParamsPartnerVo vo) {
        log.info("show: ParamsPartnerVo.toString = " + vo.toString());
        List<ResultPartnerVo> partnerRst = partnerAnalysisService.getPartner(vo);
        ResponseVo rstVo = new ResponseVo();
        rstVo.setData(partnerRst);
        return rstVo;
    }

    @RequestMapping(value = "/getpartner2", method = RequestMethod.POST)
    public ResponseVo partnerAnalysisView(@RequestBody ParamsPartnerVo vo) {
        log.info("show: ParamsPartnerVo.toString = " + vo.toString());
        List<ResultPartnerVo> partnerRst = partnerAnalysisService.getPartnerView(vo);
        ResponseVo rstVo = new ResponseVo();
        rstVo.setData(partnerRst);
        return rstVo;
    }


    /**
     * 传入feature，从人员库查找与该feature最相似的UUID
     *
     * @param feature
     * @return
     */
    @RequestMapping(value = "/locateuuid", method = RequestMethod.POST)
    public ResponseVo getFeatureUuid(@RequestParam String feature) throws IOException {
        byte[] var1 = Base64.decode(feature);

        Jedis jedis = jedisPool.getResource();
        List<byte[]> listN = Tools.getPersonRepoFeatureList();

        double[] dArr = new FeatureCompare().featureCompByByte(var1, listN);

        Map<Integer, Double> rst = Tools.getMaxScoreAndIdx(dArr);
        Map<String, String> mp = new HashMap<>();
        Iterator<Map.Entry<Integer, Double>> it = rst.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<Integer, Double> next = it.next();
            if (next.getValue().compareTo(Double.valueOf(0.7)) > 0) {
                String rowkey = jedis.lindex("rowkeyList", next.getKey());
                mp.put("uuid", rowkey);
                log.info("show: " + "找到要搜索的图片的idx= " + next.getKey() + "    相似度=" + next.getValue());
                log.info("show: " + "找到要搜索的图片的uuid= " + rowkey);
            } else {
                log.info("show: " + "没有找到要搜索的图片！");
            }
        }
        ResponseVo rstVo = new ResponseVo();
        rstVo.setData(mp);
        return rstVo;
    }

//    public Map<String, String> getFeatureUuidByRange(@RequestParam String beginTime, @RequestParam String endTime, @RequestParam String feature) throws IOException {
//        byte[] var1 = Base64.decode(feature);
//
//        List<PersonBaseVo> rstVoList = HBaseUtil.queryPartnerVo("bigdata:person-repo", beginTime, endTime);
//        List<byte[]> listN = new ArrayList<byte[]>();
//        listN = rstVoList.stream().map(e -> Base64.decode(e.getFeature())).collect(Collectors.toList());
//
//        double[] dArr = new FeatureCompare().featureCompByByte(var1, listN);
//
//        Map<Integer, Double> rst = Tools.getMaxScoreAndIdx(dArr);
//        Map<String, String> mp = new HashMap<>();
//        Iterator<Map.Entry<Integer, Double>> it = rst.entrySet().iterator();
//        while (it.hasNext()) {
//            Map.Entry<Integer, Double> next = it.next();
//            if (next.getValue().compareTo(Double.valueOf(0.7)) > 0) {
//                mp.put("uuid", rstVoList.get(next.getKey()).getUuid());
//                log.info("show: " + "找到要搜索的图片的idx= " + next.getKey() + "    相似度=" + next.getValue());
//                log.info("show: " + "找到要搜索的图片: " + rstVoList.get(next.getKey()));
//            } else {
//                log.info("show: " + "没有找到要搜索的图片！");
//            }
//        }
//        return mp;
//    }


    /**
     * 传入图片和时间范围，查找与该图片最相似的UUID
     *
     * @param pic
     * @param startTime
     * @param endTime
     * @return
     */
//    @RequestMapping(value = "/locatepicuuid", method = RequestMethod.POST)
//    public List<PersonBaseVo> getPicUuidByRange(@RequestParam String startTime, @RequestParam String endTime, @RequestParam MultipartFile pic) throws IOException {
//        String f1 = FeatureUtil.getFeatureStrByMultipartFile(pic);
//        log.info("picFeature= " + f1);
//        byte[] var1 = Base64.decode(f1);
//
//        List<PersonBaseVo> rstVoList = HBaseUtil.queryPartnerVo("bigdata:person-repo", startTime, endTime);
//        List<byte[]> listN = new ArrayList<byte[]>();
//        listN = rstVoList.stream().map(e -> Base64.decode(e.getFeature())).collect(Collectors.toList());
//
//        double[] dArr = new FeatureCompare().featureCompByByte(var1, listN);
//
//        Map<Integer, Double> rst = Tools.getMaxScoreAndIdx(dArr);
//        List<PersonBaseVo> voListRst = new ArrayList<PersonBaseVo>();
//        Iterator<Map.Entry<Integer, Double>> it = rst.entrySet().iterator();
//        while (it.hasNext()) {
//            Map.Entry<Integer, Double> next = it.next();
//            if (next.getValue().compareTo(Double.valueOf(0.7)) > 0) {
//                voListRst.add(rstVoList.get(next.getKey()));
//                log.info("show: " + "找到要搜索的图片的idx= " + next.getKey() + "    相似度=" + next.getValue());
//                log.info("show: " + "找到要搜索的图片: " + voListRst.get(0));
//            } else {
//                log.info("show: " + "没有找到要搜索的图片！");
//            }
//        }
//        return voListRst;
//    }


//    @RequestMapping(value = "/partner", method = RequestMethod.POST)
//    public List<BaseVo> partnerAnalysis(@RequestBody ParamsPartnerVo vo) {
//
//        log.info("show: vo.toString = " + vo.toString());
////        List<BaseVo> voList = partnerAnalysisService.getPartner(vo);
//
//        //HBase坏了 暂时从Mysql查数据
//        List<BaseVo> voList = personService.query(Integer.valueOf(vo.getCameraId()));
//
//        byte[] var1 = Base64.decode(vo.getFeature());
//        List<byte[]> listN = new ArrayList<byte[]>();
//        listN = voList.stream().map(e -> Base64.decode(e.getFeature())).collect(Collectors.toList());
//        double[] dArr = new FeatureCompare().featureCompByByte2(var1, listN);
//
//        Double[] dArrD = ArrayUtils.toObject(dArr);
//        List dArrList = Arrays.asList(dArrD);
//        dArrList.forEach(System.out::println);
//        Map<Integer, Double> rst = Tools.getMaxScoreAndIdx(dArr);
//        List<BaseVo> voListRst = new ArrayList<BaseVo>();
//        Iterator<Map.Entry<Integer, Double>> it = rst.entrySet().iterator();
//        while (it.hasNext()) {
//            Map.Entry<Integer, Double> next = it.next();
//            if (next.getValue().compareTo(Double.valueOf(0.7)) > 0) {
//                log.info("show: " + "找到要搜索的图片的idx= " + next.getKey());
//                final String uuid = voList.get(next.getKey()).getUuid();
//                voListRst = voList.stream().filter(x -> x.getUuid().equals(uuid)).collect(Collectors.toList());
//            } else {
//                log.info("show: " + "没有找到要搜索的图片,无同行人！");
//            }
//        }
//        for (BaseVo base : voListRst) {
//
//
//        }
//
//
//        return voListRst;
//    }

    /**
     * 从Redis插入单条pid_vid数据到Mysql
     *
     * @param pass_id
     * @return
     */
    @RequestMapping(value = "/insertPidVid", method = RequestMethod.GET)
    public Integer insertPidVid(@RequestParam("pass_id") String pass_id) {
        String uuid = jedisPool.getResource().hget("180723_pid_vid", pass_id);
        PidVidVo vo = new PidVidVo();
        vo.setDt("180723");
        vo.setUuid(uuid);
        vo.setPass_id(pass_id);

        return pidVidService.insertPidVid(vo);
    }

    /**
     * 从Redis批量插入一天的pid_vid数据到Mysql
     *
     * @param dt
     * @return
     */
    @RequestMapping(value = "/insertPidVids/{dt}", method = RequestMethod.GET)
    public Integer insertPidVids(@PathVariable("dt") String dt) {
        String key = dt + "_pid_vid";
        Map<String, String> mp = jedisPool.getResource().hgetAll(key);
        Iterator<Map.Entry<String, String>> it = mp.entrySet().iterator();
        List<PidVidVo> voList = new ArrayList<>();
        int i = 0;
        int total = 0;
        while (it.hasNext()) {
            Map.Entry<String, String> en = it.next();
            PidVidVo vo = new PidVidVo();
            vo.setPass_id(en.getKey());
            vo.setUuid(en.getValue());
            vo.setDt(dt);
            voList.add(vo);
            i++;
            if (i % 10000 == 0) {
                total += pidVidService.insertPidVids(voList);
                voList.clear();
            }
        }
        if (voList.size() != 0) {
            total += pidVidService.insertPidVids(voList);
        }
        log.info("total=" + total);
        mp.clear();
        voList.clear();
        return total;
    }

}
